package com.hzx.security.handler;

import com.hzx.security.security.TokenManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;
import utils.R;
import utils.ResponseUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TokenLogoutHandler implements LogoutHandler {


    private TokenManager tokenManager;


    private RedisTemplate redisTemplate;

    public TokenLogoutHandler(TokenManager tokenManager,RedisTemplate redisTemplate){
        this.redisTemplate = redisTemplate;
        this.tokenManager = tokenManager;
    }

    @Override
    public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
        //从header获取token
        String token = request.getHeader("token");


//        token不为空   移除token
        if(null != token){
            tokenManager.removeToken(token);

            String userInfo = tokenManager.getUserInfoByToken(token);
            redisTemplate.delete(userInfo);
        }
        ResponseUtil.out(response, R.ok());
    }
}
